﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;


namespace UnsafeCode
{
    class Program
    {
        private delegate void MethodInvoker();
        /// <summary>
        ///  通过委托执行不安全的代码
        /// </summary>
        /// <param name="args"></param>
        static int Main(string[] args)
        {
            byte[] redpill =
            {
                0x0f,0x01,0x0d,         //asm SIDI instruction
                0x00,0x00,0x00,0x00,    //placeholder for an address
                0xc3                    //asm return instruction
            };
            unsafe
            {
                fixed(byte* matrix = new byte[6], 
                    redpillPtr = redpill)
                {
                    *(uint*)&redpillPtr[3] = (uint)&matrix[0];

                    using(VirtualMemoryPtr codeBytePtr = new VirtualMemoryPtr(redpill.Length))
                    {
                        Marshal.Copy(
                            redpill, 0,
                            codeBytePtr.AllocatePointer, redpill.Length
                            );
                        MethodInvoker method = (MethodInvoker)Marshal.GetDelegateForFunctionPointer(codeBytePtr.AllocatePointer, typeof(MethodInvoker));
                        method();
                    }
                    if(matrix[5] > 0xd0)
                    {
                        Console.WriteLine("Inside Matrix");
                        return 1;
                    }
                    else
                    {
                        Console.WriteLine("Not in Matrix");
                        return 0;
                    }

                }

            }
        }
    }


}
